package jumpingnotes.dao.hibernate;

import java.util.List;

import jumpingnotes.dao.ChapterVersionDao;
import jumpingnotes.model.entity.ChapterVersion;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

public class ChapterVersionHibernateDao extends GenericHibernateDao<ChapterVersion> implements ChapterVersionDao
{
	public ChapterVersionHibernateDao()
	{
		super(ChapterVersion.class);
	}

	@SuppressWarnings("unchecked")
	public List<ChapterVersion> findValueByChapterIdAndProperty(final int chapterId, final String property)
	{
		return (List<ChapterVersion>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select cv from ChapterVersion cv where cv.chapter.chapterId=:chapterId and cv.property=:property order by cv.weight desc");
				query.setInteger("chapterId", chapterId);
				query.setString("property", property);
				return query.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public List<ChapterVersion> findChapterVersionByChapterId(final int chapterId, final int firstResult,
			final int maxResults)
	{
		return (List<ChapterVersion>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session
						.createQuery("select distinct cv from ChapterVersion cv where cv.chapter.chapterId=:chapterId");
				query.setInteger("chapterId", chapterId);

				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);

				return query.list();
			}
		});
	}
}
